package com.sanpu.kxe.business.main.presenter;

import android.app.Activity;
import android.graphics.Bitmap;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.sanpu.library.imagechoose.PhotoPreview;
import com.sanpu.kxe.business.main.contract.OldAuthSecondStepContract;
import com.sanpu.kxe.business.main.view.OldCertificateSecondActivity;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.module.luban.Luban;
import com.sanpu.kxe.module.luban.OnRenameListener;
import com.sanpu.kxe.utils.FileUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Description：人工审核第一步
 * Created by 薛勇军 on 2019/5/15.
 */

public class OldAuthSecondStepPresenter implements OldAuthSecondStepContract.Presenter {

    private OldAuthSecondStepContract.View mView;

    private HashMap<String, File> imgFiles;

    public OldAuthSecondStepPresenter(OldAuthSecondStepContract.View mView) {
        this.mView = mView;
        imgFiles = new HashMap<>();
    }

    @Override
    public void takePhoto(String photo, int code) {
        ArrayList<String> photoPaths = new ArrayList<>();
        photoPaths.add(photo);
        PhotoPreview.builder()
                .setPhotos(photoPaths)
                .setCurrentItem(0)
                .start((Activity) mView.getContext(), code);
    }

    @Override
    public void onCompress(String filePath, final String reName) {
        try {
            final OldCertificateSecondActivity activity = (OldCertificateSecondActivity) mView.getContext();
            activity.showLoadingDialog(false, "照片压缩处理中...");
            //同步方法请尽量避免在主线程调用以免阻塞主线程
            Observable.just(filePath)
                    .observeOn(Schedulers.io())
                    .map(new Func1<String, List<File>>() {
                        @Override
                        public List<File> call(String filePath) {
                            return luban(filePath, reName);
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<File>>() {
                        @Override
                        public void onCompleted() {
                            activity.dismissLoadingDialog();
                        }

                        @Override
                        public void onError(Throwable e) {
                            activity.dismissLoadingDialog();
                        }

                        @Override
                        public void onNext(List<File> files) {
                            if (files != null && files.size() > 0) {
                                imgFiles.put(reName, files.get(0));
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * luban图片压缩
     *
     * @param filePath 图片地址
     * @param reName   重命名
     * @return
     */
    private List<File> luban(String filePath, final String reName) {
        try {
            // 同步方法直接返回压缩后的文件
            return Luban.with(mView.getContext())
                    .load(filePath)
                    .ignoreBy(CommonConfig.LUBAN_COMPRESSSIZE)
                    .isNeedDesired(true)
                    .desiredValue(CommonConfig.LUBAN_COMPRESSSIZE)
                    .setRenameListener(new OnRenameListener() {
                        @Override
                        public String rename(String filePath) {
                            return reName + "_" + System.currentTimeMillis();
                        }
                    })
                    .get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取网络图片文件
     */
    @Override
    public void getImageFileByNet(String imageUrl, final String fileName) {
        Glide.with(mView.getContext())
                .load(imageUrl)//强制Glide返回一个Bitmap对象
                .asBitmap()
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                        if (bitmap != null) {
                            String filePath = FileUtil.compressAndSave(bitmap, fileName);
                            File imageFile = null;
                            if (!TextUtils.isEmpty(filePath)) {
                                imageFile = new File(filePath);
                            }
                            if (imageFile != null && imageFile.exists()) {
                                if (imgFiles == null) {
                                    imgFiles = new HashMap<>();
                                }
                                imgFiles.put(fileName, imageFile);
                            }
                            if (imgFiles.size() > 1) {
                                mView.dismissLoadingDialog();
                            }
                        }
                    }
                });
    }

    @Override
    public void removeFile(String fileKey) {
        if (imgFiles != null && imgFiles.containsKey(fileKey)) {
            imgFiles.remove(fileKey);
        }
    }

    @Override
    public HashMap<String, File> getFiles() {
        return imgFiles;
    }

    @Override
    public void setImgFiles(HashMap<String, File> imgFiles) {
        this.imgFiles = imgFiles;
    }

    @Override
    public void onDestroyPresenter() {

    }
}
